/**
 * @file BleProtocol.c
 * @brief 
 * @author xuesong (wenshaoliu@foxmail.com)
 * @version 1.0
 * @date 2024-11-05
 * 
 * @copyright Copyright (c) 2024  by xuesong
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2024-11-05     <td>1.0     <td>xuesong   <td>内容
 * </table>
 */
#include <stdlib.h>
#include <string.h>
#ifndef osal_mem_alloc
#define osal_mem_alloc        malloc
#endif
#ifndef osal_mem_free
#define osal_mem_free         free
#endif
#ifndef osal_memcpy
#define osal_memcpy           memcpy
#endif
#include "log.h"
//---------------------------------------------------
#include "BleProtocol.h"
#include "log.h"
//-----------------------------------------------------------------
#ifndef     USER_TASK_START
#define     USER_TASK_START         0
#define     USER_TASK_STOP          1
#endif
//------------------------------------------------------
uint8_t dataXorCheck(uint16_t len, uint8_t *data)
{
    uint8_t ret = 0;
    
    for(uint16_t i=0; i<len; i++)
    {
        ret ^= data[i];
    }
    return ret;
}

uint8_t Pack2BleNotify(uint8_t cmd,uint8_t *data,uint16_t len)
{
    BleAppCmdData_t *pBleAppCmd = NULL;
    BleAppCmdData_t BleAppCmd = {
        .head = BLE_APP_CMD_HEAD,
        .cmd = cmd,
    };
    uint8_t *pData = NULL;
    if(len < BLE_STRUCT_DATA_LEN)
    {
        if(len)
            osal_memcpy(BleAppCmd.data,data,len);
        pBleAppCmd = &BleAppCmd;
    }
    else{
        pData = osal_mem_alloc(len+4);
        pBleAppCmd = (BleAppCmdData_t *)pData;
        pBleAppCmd->head = BLE_APP_CMD_HEAD;
        pBleAppCmd->cmd = cmd;
        if(pBleAppCmd != NULL)
            osal_memcpy(pBleAppCmd->data,data,len);
    }
    if(pBleAppCmd != NULL)
    {
        pBleAppCmd->len = len;
        pBleAppCmd->data[len] = dataXorCheck(len + 2,&pBleAppCmd->cmd);
        // xStreamBufferWrite(&xStreamBleTx,pBleAppCmd,pBleAppCmd->len+4);
        // Transmit_task_set(USER_TASK_START, TrasmitEvent_BleApp_TX, 5);
        printf("pack frame:");
        LOG_DUMP(pBleAppCmd,pBleAppCmd->len+4);
        if(pBleAppCmd != &BleAppCmd)
        {
            osal_mem_free(pBleAppCmd);
        }
    }
    return 0;
}
// /**
//  * @brief 
//  * @param  weight          0.01g
//  * @return uint8_t 
//  */
// uint8_t PackWeight2App(int32_t weight)
// {
//     uint8_t data[3];
//     if(!ScaleWeight.Flag.Bit.WtNew)
//         return 0;
//     // if(ScaleWeight.Flag.Bit.overLoad)
//     if(weight < 0)
//     {
//         weight = 0 - weight;
//         data[0] = 0x80;
//     }
//     data[2] = weight&0xFF;
//     weight >>= 8;
//     data[1] = weight&0xFF;
//     weight >>= 8;
//     data[0] |= weight&0xFF;
//     return Pack2BleNotify(BLE_APP_CMD_WEIGHT,data,3);  
// }

// uint8_t PackTare2App(void)
// {
//     uint8_t value = 1;
//     if(ScaleWeight.Flag.Bit.appTare)
//     {
//         ScaleWeight.Flag.Bit.appTare = false;
//         return Pack2BleNotify(BLE_APP_CMD_TARE,&value,1);  
//     }else{
//         return Pack2BleNotify(BLE_APP_CMD_TARE|BLE_APP_CMD_MASK,&value,1);  
//     }
// }
// /**
//  * @brief 
//  * @param  time_second      MyParamDoc
//  * @return uint8_t 
//  */
// uint8_t PackTime2App(uint16_t time_second)
// {
//     static uint16_t lastSendSecond = 0;
//     uint8_t data[2];
//     if(!coffeeWeightAndTimer.Flag.Bit.RunTimer || lastSendSecond == time_second)
//         return 0;
//     lastSendSecond = time_second;
//     data[1] = time_second&0xFF;
//     time_second >>= 8;
//     data[0] = time_second&0xFF;
//     return Pack2BleNotify(BLE_APP_CMD_TIME|BLE_APP_CMD_MASK,data,2);  
// }

// /**
//  * @brief 
//  * @param  speed            0.1g/s
//  * @return uint8_t 
//  */
// uint8_t PackWaterSpeed2App(uint32_t speed)
// {
//     uint8_t data[2];
//     if(!waterFlow.Flag.Bit.WaterFlowIng || !UserProcess.clockflag.flagBit.HalfSecond)
//         return 0;
//     data[1] = speed&0xFF;
//     speed >>= 8;
//     data[0] = speed&0xFF;
//     return Pack2BleNotify(BLE_APP_CMD_SPEED|BLE_APP_CMD_MASK,data,2);  
// }


/**
 * @brief 
 * @param  data             MyParamDoc
 * @param  len              MyParamDoc
 */
void ProcessAppCmd(uint8_t *data,uint16_t len)
{
    uint16_t index = 0;
    uint8_t xorCheckValue = 0;
    uint8_t AckValue = 0;
    BleAppCmdData_t *bleAppCmdData = NULL;
    while(len)
    {
        if(len >= 4)
        {
            bleAppCmdData = (BleAppCmdData_t *)&data[index];
            xorCheckValue = dataXorCheck(bleAppCmdData->len+2,&bleAppCmdData->cmd);
            if(xorCheckValue != bleAppCmdData->data[bleAppCmdData->len] || bleAppCmdData->head != BLE_APP_CMD_HEAD)
            {
                index++;
                len--;
                continue;
            }
            switch (bleAppCmdData->cmd &(~BLE_APP_CMD_MASK))
            {
                case    BLE_APP_CMD_WEIGHT:
                        break;
                case    BLE_APP_CMD_TARE:       //去皮
                        {
                            LOG("data = %x\r\n",bleAppCmdData->data[0]);
                            // if(bleAppCmdData->cmd & BLE_APP_CMD_MASK)
                            // {
                            //     ScaleWeight.Flag.Bit.tare = TRUE;
                            //     ScaleWeight.Flag.Bit.appTare = TRUE;        //app 去皮指令，不用发送重量清零指令给APP
                            // }else{
                            //     ;                                           //app 回复设备清零指令，暂时不用处理
                            // }
                        }
                        break;
                case    BLE_APP_CMD_UNIT:
                        {
                            // if(bleAppCmdData->cmd & BLE_APP_CMD_MASK)
                            // {
                            //     if(bleAppCmdData->data[0] >= WEIGHT_UNIT_MIN && bleAppCmdData->data[0] < WEIGHT_UNIT_MAX)
                            //     {
                            //         coffeMacInfor.WeightUnit = bleAppCmdData->data[0];
                            //         coffeMacInfor.Flag.Bit.Change = true;
                            //     }
                            //     Pack2BleNotify(BLE_APP_CMD_UNIT,&coffeMacInfor.WeightUnit,1); //app 切单位，需要回复
                            // }
                        }
                        break;
                case    BLE_APP_CMD_SLEEP:
                        break;
                case    BLE_APP_CMD_BATTERY:
                        break;
                case    BLE_APP_CMD_CONNECT:                                //蓝牙连接状态
                        break;
                case    BLE_APP_CMD_TIME:                                   //蓝牙同步计时
                        break;
                case    BLE_APP_CMD_START_TIME:                             //蓝牙启动计时
                        {
                            if(bleAppCmdData->cmd & BLE_APP_CMD_MASK)
                            {
                                // if(UserProcess.process == D_USER_PROCESS_HandleMode || D_USER_PROCESS_HandleAtuoT == UserProcess.process)
                                // {
                                //     coffeWeightAndTimer.Flag.Bit.startTimer = true;
                                //     coffeWeightAndTimer.Flag.Bit.AppTrigTimer = true;
                                //     AckValue = 01;                          //收到
                                // }else{
                                //     AckValue = 00;                          //失败
                                // }
                                // Pack2BleNotify(bleAppCmdData->cmd &(~BLE_APP_CMD_MASK),&AckValue,1); //app 切单位，需要回复
                            }

                        }
                        break;        
                case    BLE_APP_CMD_STOP_TIME:                              //蓝牙停止计时
                        {
                            if(bleAppCmdData->cmd & BLE_APP_CMD_MASK)
                            {
                                // if(UserProcess.process == D_USER_PROCESS_HandleMode || D_USER_PROCESS_HandleAtuoT == UserProcess.process)
                                // {
                                //     coffeWeightAndTimer.Flag.Bit.startTimer = true;
                                //     coffeWeightAndTimer.Flag.Bit.AppTrigTimer = true;
                                //     AckValue = 02;                          //收到
                                // }else{
                                //     AckValue = 00;                          //失败
                                // }
                                // Pack2BleNotify(bleAppCmdData->cmd &(~BLE_APP_CMD_MASK),&AckValue,1); //app 切单位，需要回复
                            }

                        }
                        break;        
                case    BLE_APP_CMD_CLR_TIME:                               //清除计时
                        {
                            // if(bleAppCmdData->cmd & BLE_APP_CMD_MASK)
                            // {
                            //     coffeWeightAndTimer.Flag.Bit.ResetTimer = TRUE; // 重置
                            //     coffeWeightAndTimer.Flag.Bit.AppTrigTimer = true;
                            //     AckValue = 02;                          //收到
                            //     Pack2BleNotify(bleAppCmdData->cmd &(~BLE_APP_CMD_MASK),&AckValue,1); //app 切单位，需要回复
                            // }
                        }
                        break;
                default:
                    break;
            }
            if(len > (bleAppCmdData->len+4))
            {
                len -= (bleAppCmdData->len + 4);
            }else{
                break;
            }
        }else{
            LOG("data frame err:");
            LOG_DUMP_BYTE(&data[index],len);
            break;                      //数据异常
        }
    }

}


